#include <iostream>
#include <fstream>
#include <sstream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

int levantarPlanos(const char *file, int mode, const char *out){

	string line=""; 
	
	ifstream ifile; 
	
	ifile.open( file );

	getline( ifile, line );		
	if( line.compare("#") == 0 ) return 0;

	char outfile[200];
	
	sprintf( outfile, "%s.dot", out);
		
	ofstream ofile;
	ofile.open( outfile );
    
    
    /*****************************/
	  int k, m, c_i, c_j;
	  
	  sscanf( line.c_str(), "%d %d", &k, &m );
	  
	  getline( ifile, line );
	  istringstream iss( line );

	  if (mode == 1) {
		ofile << "Graph G{\n";
	  } else if (mode == 2) {
		ofile << "Digraph G{\n";
	  } else {
		printf("Modo no valido\n");
		return 1;  
	  }
	  
	  for( int i = 1; i <= k; i++ ){
		  ofile << i << ";\n";
	  }

	  int i = 0;
	  do{
		  getline( ifile, line );
		  istringstream iss( line );	
		  
		  iss >> c_i; iss >> c_j;
		  if (mode == 1) {
			ofile << c_i << " -- " << c_j << ";\n";
		  } else if (mode == 2) {
			ofile << c_i << " -> " << c_j << ";\n";
		  }  
	  }while(++i<m);
	  ofile << "}\n";
		
	  /****************************/
	  ofile.close();

	ifile.close();
	return 0;
	
}

int main(int argc, char* argv[]){
	if( argc < 4 ){
		printf( "1) Nombre del input\n 2) Modo (grafo:1 || digrafo:2)\n 3) Nombre del output\n" );
		return 1;
	}	

	const char* input_file = argv[1];
	int input_mode = atoi(argv[2]);
	char* output_file = argv[3];
	
	levantarPlanos(input_file, input_mode, output_file);
	
	std::ostringstream command;

	if (input_mode == 1) {
		command << "neato " << output_file << ".dot -Tpng -o " << output_file << ".png";
		system (command.str().c_str());
	} else if (input_mode == 2) {
		command << "dot " << output_file << ".dot -Tpng -o " << output_file << ".png";
		system (command.str().c_str());
	}

	return 0;
}
